package io.github.biezhi.elves.utils;

import java.awt.Font;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.SocketTimeoutException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.util.TextUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.openqa.selenium.os.WindowsUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import io.github.biezhi.elves.common.Constants;
import io.github.biezhi.elves.ok.http.FastHttpClient;
import io.github.biezhi.elves.selenium.QccSelenium;

public class StringUtils {

	/**
	 * 输出printStackTrace内容
	 * 
	 * @param e
	 * @return
	 */
	public static String getErrorInfoFromException(Exception e) {
		try {
			StringWriter sw = new StringWriter();
			PrintWriter pw = new PrintWriter(sw);
			e.printStackTrace(pw);
			return "\r\n" + sw.toString();
		} catch (Exception e2) {
			return "bad getErrorInfoFromException";
		}
	}
	
	public static boolean isEmpty(String s) {
		int i;
		if (s == null || (i = s.length()) == 0)
			return true;

		for (int j = 0; j < i; j++)
			if (!Character.isWhitespace(s.charAt(j)))
				return false;

		return true;
	}

	public static boolean isNumeric(String s) {
		if (s == null)
			return false;
		// s = s.trim();
		int i = s.length();

		if (i <= 0)
			return false;

		for (int j = 0; j < i; j++)
			if (!Character.isDigit(s.charAt(j)))
				return false;

		return true;
	}

	public static final int HIGHEST_SPECIAL = 62;

	public static char specialCharactersRepresentation[][];

	public static String escapeXml(String buffer) {
		int start = 0;
		int length = buffer.length();
		char arrayBuffer[] = buffer.toCharArray();
		StringBuffer escapedBuffer = null;
		for (int i = 0; i < length; i++) {
			char c = arrayBuffer[i];
			if (c > '>')
				continue;
			char escaped[] = specialCharactersRepresentation[c];
			if (escaped == null)
				continue;
			if (start == 0)
				escapedBuffer = new StringBuffer(length + 5);
			if (start < i)
				escapedBuffer.append(arrayBuffer, start, i - start);
			start = i + 1;
			escapedBuffer.append(escaped);
		}

		if (start == 0)
			return buffer;
		if (start < length)
			escapedBuffer.append(arrayBuffer, start, length - start);
		return escapedBuffer.toString();
	}

	public static String URLEncode(String s, String enc) {
		if (s == null)
			return "null";
		if (enc == null)
			enc = "UTF-8";
		StringBuffer out = new StringBuffer(s.length());
		ByteArrayOutputStream buf = new ByteArrayOutputStream();
		OutputStreamWriter writer = null;
		try {
			writer = new OutputStreamWriter(buf, enc);
		} catch (UnsupportedEncodingException ex) {
			writer = new OutputStreamWriter(buf);
		}
		for (int i = 0; i < s.length(); i++) {
			int c = s.charAt(i);
			if (c == 32) {
				out.append('+');
				continue;
			}
			if (isSafeChar(c)) {
				out.append((char) c);
				continue;
			}
			try {
				writer.write(c);
				writer.flush();
			} catch (IOException e) {
				buf.reset();
				continue;
			}
			byte ba[] = buf.toByteArray();
			for (int j = 0; j < ba.length; j++) {
				out.append('%');
				out.append(Character.forDigit(ba[j] >> 4 & 0xf, 16));
				out.append(Character.forDigit(ba[j] & 0xf, 16));
			}

			buf.reset();
		}

		return out.toString();
	}

	private static boolean isSafeChar(int c) {
		if (c >= 97 && c <= 122)
			return true;
		if (c >= 65 && c <= 90)
			return true;
		if (c >= 48 && c <= 57)
			return true;
		return c == 45 || c == 95 || c == 46 || c == 33 || c == 126 || c == 42 || c == 39 || c == 40 || c == 41;
	}

	static {
		specialCharactersRepresentation = new char[63][];
		specialCharactersRepresentation[38] = "&amp;".toCharArray();
		specialCharactersRepresentation[60] = "&lt;".toCharArray();
		specialCharactersRepresentation[62] = "&gt;".toCharArray();
		specialCharactersRepresentation[34] = "&#034;".toCharArray();
		specialCharactersRepresentation[39] = "&#039;".toCharArray();
	}

	/**
	 * 方法说明：把字符串数组转换为字符串 创建人： 卢振文 创建时间：2009-09-02 参数说明：array-字符串数组，separator-分割符
	 */
	public static String chageStringArray(String[] array, String separator) {
		String str = "";
		if (array != null && array.length > 0) {
			int len = array.length;
			for (int i = 0; i < len; i++) {
				str += array[i];
				if (i < len - 1)
					str += separator;
			}
		}
		return str;
	}

	/**
	 * 方法说明：判断字符串是否为空 创建人： 卢振文 创建时间：2009-09-02 参数说明：str-字符串
	 */
	public static boolean isNullOrEmpty(String str) {
		if (str != null && !str.trim().equals(""))
			return false;
		return true;
	}

	/**
	 * 方法说明：判断两个字符串是否相等 创建人： 卢振文 创建时间：2009-09-02 参数说明：str1-字符串,str2-字符串
	 */
	public static boolean isEquals(String str1, String str2) {
		boolean flag = false;
		if (str1 == null && str2 == null)
			flag = true;
		else if ((str1 == null && str2 != null) || (str1 != null && str2 == null))
			flag = false;
		else if (str1.trim().equals(str2.trim()))
			flag = true;
		return flag;
	}

	/**
	 * 方法说明：转换字符串 创建人： 卢振文 创建时间：2009-09-02 参数说明：obj-对象
	 */
	public static String toString(Object obj) {
		if (obj != null)
			return obj.toString();
		return null;
	}

	/**
	 * 方法说明：转换字符串 创建人： 卢振文 创建时间：2009-10-16 参数说明：obj-对象
	 */
	public static String toString2(Object obj) {
		if (obj != null)
			return obj.toString();
		return "";
	}

	/**
	 * 方法说明：转换字符串 创建人： 卢振文 创建时间：2009-10-16 参数说明：objStr-对象
	 */
	public static String toString3(String objStr) {
		if (!"null".equals(objStr) && !isNullOrEmpty(objStr))
			return objStr;
		return "";
	}

	/**
	 * 方法说明：截取某字符串中，以separator为分割的第n个分割符开始截取第m个字符串。 如：全省—深圳—产品—我的e家
	 * subString(“全省—深圳—产品—我的e家”,“—”,3,4) 结果：我的e家 创建人： 卢振文 创建时间：2011-12-06
	 * 参数说明：obj-对象，separator-分割符，n-起始位置，m-结束位置
	 */
	public static String subString(String obj, String separator, int n, int m) {
		StringBuffer result = new StringBuffer();
		if (obj != null) {
			String[] tmpAry = obj.split(separator);
			if (tmpAry != null) {
				for (int s = tmpAry.length >= m ? m : tmpAry.length; n < s; n++) {
					result.append(tmpAry[n]);
					if (s != n + 1)
						result.append(separator);
				}
				if (result.length() == 0) {// 如没有截取到则截取最后一个分隔符后的字符串
					int pos = obj.lastIndexOf(separator);
					result.append(obj.substring(pos == -1 ? 0 : pos + 1));
				}
			}
		}
		return result.toString();
	}

	/**
	 * 方法说明：获取字符长度（英文占1长度，中文占2长度） 创建人： 卢振文
	 */
	public static int getStrLen(String s) {
		if (s == null)
			return -1;
		String tmp = "";
		try {
			tmp = new String(s.getBytes("GBK"), "ISO8859_1");
		} catch (UnsupportedEncodingException e) {
			tmp = s;
		}
		return tmp.length();
	}

	/**
	 * 方法说明：去掉空格 创建人： 李绍樟 创建时间：2009-10-16 参数说明：obj-对象
	 */
	public static String delBlank(String s) {
		s = s.trim();
		// s=s.replace("·", "、");
		// s = s.replaceAll(" ", "");
		return s;
	}

	/**
	 * 
	 * 方法说明：去掉字符串里的符号 创建人： 李绍樟 创建时间：2009-11-3 参数说明：
	 */
	public static String deleteStopWord(String astr) {
		boolean result = false;
		StringBuffer sb = new StringBuffer();
		String[] stopword = { "、", "，", "；", ":", "‘", "’", "”", "“", "。", "？", "【", "】", "{", "}", // 汉字标点
				",", ";", ":", "\"", "'", "[", "]", "(", ")", "&", "*", "!", "$", "#", "@", "%", "+", "-", "_", "=",
				"~", "<", ">", "?", // 国际标点
				/*
				 * "1", "2", "3", "4", "5", "6", "7", "8", "9", "0" //单位数字
				 */// "的","一","不","在","人","有","是","为","以","于",
					// "上","他","而","后","之","来","及","了","因","下","可",
		};
		for (int i = 0; i < astr.length(); i++) {
			char g = astr.charAt(i);
			String h = String.valueOf(g);
			for (int a = 0; a < stopword.length; a++) {
				if (h.equals(stopword[a])) {
					result = true;
					break;
				} else {
					result = false;
				}
			}
			if (result == false) {
				sb.append(h);
			}
		}
		return sb.toString();

	}

	public static String replaceSpecialCharacter(String SpecialCharacter) {
		for (int y = 0; y < SpecialCharacter.length(); y++) {
			char ch = SpecialCharacter.charAt(y);
			if (ch == '+') {
				SpecialCharacter = SpecialCharacter.replace(ch, '＋');
			}
			if (ch == '#') {
				SpecialCharacter = SpecialCharacter.replace(ch, '＃');
			}
			if (ch == '%') {
				SpecialCharacter = SpecialCharacter.replace(ch, '％');
			}
			if (ch == '&') {
				SpecialCharacter = SpecialCharacter.replace(ch, '＆');
			}
			if (ch == '\'') {
				SpecialCharacter = SpecialCharacter.replace(ch, '_');
			}

		}
		return SpecialCharacter;
	}

	@SuppressWarnings("rawtypes")
	public static Map listToMap(List list) {
		Map map = new HashMap();
		if (list.size() > 0) {
			map = (Map) list.get(0);
		}
		return map;
	}

	/**
	 * 获取混合字符串长度
	 * 
	 * @param str
	 * @return
	 */
	public static int countWords(String str) {
		if (str == null || str.length() <= 0) {
			return 0;
		}
		int len = 0;
		char c;
		for (int i = str.length() - 1; i >= 0; i--) {
			c = str.charAt(i);
			if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
				// 字母, 数字
				len++;
			} else {
				if (Character.isLetter(c)) { // 中文
					len += 2;
				} else { // 符号或控制字符
					len++;
				}
			}
		}
		return len;
	}

	/**
	 * 字符串按字节截取
	 * 
	 * @param str
	 *            原字符
	 * @param len
	 *            截取长度
	 * @return String
	 */
	public static String splitString(String str, int len) {
		return splitString(str, len, "...");
	}

	/**
	 * 字符串按字节截取
	 * 
	 * @param str
	 *            原字符
	 * @param len
	 *            截取长度
	 * @param elide
	 *            省略符
	 * @return String
	 */
	public static String splitString(String str, int len, String elide) {
		if (str == null) {
			return "";
		}
		byte[] strByte = str.getBytes();
		int strLen = strByte.length;
		int elideLen = (elide.trim().length() == 0) ? 0 : elide.getBytes().length;
		if (len >= strLen || len < 1) {
			return str;
		}
		if (len - elideLen > 0) {
			len = len - elideLen;
		}
		int count = 0;
		for (int i = 0; i < len; i++) {
			int value = (int) strByte[i];
			if (value < 0) {
				count++;
			}
		}
		if (count % 2 != 0) {
			len = (len == 1) ? len + 1 : len - 1;
		}
		return new String(strByte, 0, len) + elide.trim();
	}

	/**
	 * 替换A标签处理方法
	 * 
	 * @param tag
	 *            参数说明:源目标
	 * @param repCont
	 *            参数说明:替换内容
	 * @return
	 */
	public static String filterTagA(String tag, String repCont) {
		return tag.replaceAll("<a[^>]+>", repCont).replaceAll("</a>", repCont);
	}

	/**
	 * 过滤重复
	 * 
	 * @param list
	 * @param key
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static List filterResetList(List list, String key) {
		boolean flag;
		List tempList = new ArrayList();
		List faultList = new ArrayList();
		Map map = new HashMap();
		for (int i = 0; i < list.size(); i++) {
			map = (Map) list.get(i);
			tempList = faultList;
			flag = true;
			if (tempList.size() == 0) {
				faultList.add(map);
			} else {
				for (int j = 0; j < tempList.size(); j++) {
					if (i == j)
						continue;
					if (map.get(key).equals(((Map) tempList.get(j)).get(key))) {
						flag = false;
						break;
					}
				}
				if (flag) {
					faultList.add(map);
				}
			}
		}
		return faultList;
	}

	/**
	 * 获取ID值字符串
	 * 
	 * @param idList
	 *            参数说明:集合
	 * @param collumnName
	 *            参数说明:取字段名称
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static String queryIds(List idList, String columnName, String splitType, boolean replaceFlag, int type) {
		StringBuffer sb = new StringBuffer();
		if (type == 1) {
			for (int i = 0; i < idList.size(); i++) {
				Map map = (Map) idList.get(i);
				if (i > 0) {
					sb.append(",");
				}
				sb.append("'");
				sb.append(map.get(columnName));
				sb.append("'");
			}
		}

		if (type == 2) {
			String[] ids = columnName.split(splitType);
			for (int i = 0; i < ids.length; i++) {
				if (i > 0) {
					sb.append(",");
				}
				sb.append("'");
				sb.append(replaceFlag == true ? ids[i].replace(splitType, ",") : ids[i]);
				sb.append("'");
			}
		}
		return sb.toString();
	}

	/**
	 * 判断是否存在key,不存在返回空字符
	 * 
	 * @param key
	 * @param paramMap
	 * @return
	 */
	public static boolean getBooleanForKey(String key, Map<String, Object> paramMap) {
		boolean isBoolean = false;
		String isBooleanStr = getValueForKey(key, paramMap);
		if ("true".equals(isBooleanStr)) {
			isBoolean = Boolean.valueOf(isBooleanStr);
		}
		return isBoolean;
	}

	/**
	 * 判断是否存在key,不存在返回空字符
	 * 
	 * @param key
	 * @param paramMap
	 * @return
	 */
	public static String getValueForKey(String key, Map<String, Object> paramMap) {
		if (!paramMap.containsKey(key)) {
			return "";
		}
		if ("null".equals(String.valueOf(paramMap.get(key)))) {
			return "";
		}
		return String.valueOf(paramMap.get(key));
	}

	/**
	 * 判断是否存在key,不存在返回空值 vaLen用于判断所选的值是一个还是多个
	 * 
	 * @param key
	 * @param paramMap
	 * @return
	 */
	public static String[] getArrayValueForKey(String key, Map<String, Object> paramMap) {
		if (!paramMap.containsKey(key)) {
			return null;
		}
		String valLenKeyName = "valLen" + key;
		String valLenStr = getValueForKey(valLenKeyName, paramMap);
		if ("null".equals(valLenStr)) {
			valLenStr = "";
		}
		valLenStr = "".equals(valLenStr) ? "0" : valLenStr;
		int valLen = Integer.parseInt(valLenStr);
		if (valLen > 1) {
			return getValueForKey(key, paramMap).split(",");
		} else {
			return String.valueOf(paramMap.get(key)).split(",");
		}
	}

	/**
	 * 判断是否存在key,不存在返回0
	 * 
	 * @param key
	 * @param paramMap
	 * @return
	 */
	public static int getIntValueForKey(String key, Map<String, Object> paramMap) {
		String valueForKey = getValueForKey(key, paramMap);
		valueForKey = valueForKey.replace("\n", "");
		return isNullOrEmpty(valueForKey) ? 0 : Integer.parseInt(valueForKey);
	}

	/**
	 * 判断是否存在key,不存在返回0
	 * 
	 * @param key
	 * @param paramMap
	 * @return
	 */
	public static double getDoubleValueForKey(String key, Map<String, Object> paramMap) {
		String valueForKey = getValueForKey(key, paramMap);
		return isNullOrEmpty(valueForKey) ? 0 : Double.parseDouble(valueForKey);
	}
	
	/**
	 * 判断是否存在key,不存在返回0
	 * 
	 * @param key
	 * @param paramMap
	 * @return
	 */
	public static Long getLongValueForKey(String key, Map<String, Object> paramMap) {
		String valueForKey = getValueForKey(key, paramMap);
		return isNullOrEmpty(valueForKey) ? 0L : Long.parseLong(valueForKey);
	}

	/**
	 * 用于解析客户端的escape编码
	 * 
	 * @param src
	 * @return
	 */
	public static String unescape(String src) {
		if (src == null)
			return null;
		StringBuffer tmp = new StringBuffer();
		tmp.ensureCapacity(src.length());
		int lastPos = 0, pos = 0;
		char ch;
		while (lastPos < src.length()) {
			pos = src.indexOf("%", lastPos);
			if (pos == lastPos) {
				if (src.charAt(pos + 1) == 'u') {
					ch = (char) Integer.parseInt(src.substring(pos + 2, pos + 6), 16);
					tmp.append(ch);
					lastPos = pos + 6;
				} else {
					ch = (char) Integer.parseInt(src.substring(pos + 1, pos + 3), 16);
					tmp.append(ch);
					lastPos = pos + 3;
				}
			} else {
				if (pos == -1) {
					tmp.append(src.substring(lastPos));
					lastPos = src.length();
				} else {
					tmp.append(src.substring(lastPos, pos));
					lastPos = pos;
				}
			}
		}
		return tmp.toString();
	}

	/**
	 * 返回sql语句decode排序
	 * 
	 * @param paramVal
	 * @param columnsName
	 * @return
	 */
	public static String getDecodeVisorder(String paramVal, String columnsName) {
		StringBuffer decodeStr = new StringBuffer();
		decodeStr.append("DECODE(").append(columnsName).append(",");
		if (!isNullOrEmpty(paramVal)) {
			if (paramVal.indexOf(",") != -1) {
				String[] paramValArray = paramVal.split(",");
				int n = paramValArray.length;
				for (int i = 0; i < paramValArray.length; i++) {
					int index = i + 1;
					decodeStr.append("'").append(paramValArray[i]).append("',").append(index);
					if (i != (n - 1)) {
						decodeStr.append(",");
					}
				}
			} else {
				decodeStr.append("'").append(paramVal).append("',1");
			}
		}
		decodeStr.append(") AS DECODE_VISORDER ");
		return decodeStr.toString();
	}

	/**
	 * 对字符串内容进行分组
	 * 
	 * @param inpt
	 *            参数说明:字符串内容
	 * @param groupNum
	 *            参数说明:分组数
	 * @return
	 */
	public static String getGroupStr(String inpt, String delimiter, int groupNum) {
		// "处理前:只想装一条宽带，不想装固话和手机可以选择什么套餐？";
		// "处理后:只想|装一|条宽|带，|不想|装固|话和|手机|可以|选择|什么|套餐|？|";
		int strLength;
		boolean b = true;
		StringBuffer groupVal = new StringBuffer();

		int inptLength = inpt.length();
		if (inptLength % groupNum == 0) {
			strLength = inptLength / groupNum;
		} else {
			b = false;
			strLength = (int) inptLength / groupNum + 1;
		}
		String[] str = new String[strLength];
		for (int i = 0; i < str.length; i++) {
			if (b || (i != str.length - 1))
				str[i] = inpt.substring(groupNum * i, groupNum * i + groupNum);
			else
				str[i] = inpt.substring(groupNum * i);
		}
		for (int i = 0; i < str.length; i++) {
			// System.out.print(str[i] + delimiter);
			groupVal.append(str[i]).append(delimiter);
		}
		return groupVal.toString();
	}

	/**
	 * 根据FAQID查询问题和答案
	 * 
	 * @param answer
	 * @return
	 */
	public static String getContent(String answer) {
		String reg = "<img\\s.*?>(.*?)</img>";
		Pattern r = Pattern.compile(reg);
		Matcher m = r.matcher(answer);
		while (m.find()) { // 查找图片标签
			String imgstring1 = m.group();
			String imgstring2 = m.group();
			String styleReg = "style=\"([^\"]+)\"";// 正则获得style属性
			Pattern rr = Pattern.compile(styleReg);
			Matcher mm = rr.matcher(imgstring2);

			String width = null;
			String height = null;
			String styleString = "";// 原来的
			String styleString2 = "";
			if (mm.find()) {
				styleString2 = mm.group(1);// 获得高和宽
				styleString = mm.group(1);
				styleString2 = styleString2.replace(" ", "").toLowerCase();
				String[] dd = styleString2.split(";");
				for (int i = 0; i < dd.length; i++) {
					if (dd[i].indexOf("width") != -1) {
						String dddd = dd[i].replace("width:", "").replace("px", "");
						width = dddd;
					}
					if (dd[i].indexOf("height") != -1) {
						String dddd = dd[i].replace("height:", "").replace("px", "");
						height = dddd;
					}
				}
				int widthInt = Integer.parseInt(width);// 转换成数字
				int heightInt = Integer.parseInt(height);// 转换成数字
				int afterWidthInt = 0;
				int afterHeightInt = 0;
				double compressionRatio = 0.00;// 压缩比
				if (widthInt > 121) {// 如果宽度大于121
					afterWidthInt = 121;
					compressionRatio = (double) widthInt / 121;
					afterHeightInt = (int) (heightInt / compressionRatio);
					String gg = "width:" + afterWidthInt + "px;" + "height:" + afterHeightInt + "px;";// 组装成新的大小
					// 把原来的样式替换成最新的
					imgstring2 = imgstring2.replaceAll(styleString, gg);

				}
				String srcReg = "src=\"([^\"]+)\"";// 正则获得style属性
				Pattern rrr = Pattern.compile(srcReg);
				Matcher mmm = rrr.matcher(imgstring2);
				String src = "";
				if (mmm.find()) {
					src = mmm.group(1);// 获得高和宽
				}
				String imgPath = "";
				if (src.indexOf("/ckb/") != -1 && src.indexOf("/附件/") != -1) {
					int pathPosition = src.lastIndexOf("/");
					imgPath = src.substring(pathPosition + 1, src.length());
				}

				StringBuffer imgText = new StringBuffer();
				imgText.append("<a class='imgshow' id='").append(imgPath).append("' href='").append(src)
						.append("' title=\"<div><a href=javascript:showImg('").append(imgPath)
						.append("'); >查看原图</a></div>\" >").append(imgstring2).append("</a>");

				// 把原来的内容替换成样式
				answer = answer.replaceAll(imgstring1, imgText.toString());
			}
		}
		return answer;
	}

	/**
	 * 匹配href的字符串链接(格式href='或"xxxx'或")
	 * 
	 * @param paramHtml
	 * @return
	 */
	public static Matcher matchHrefGroup(String paramHtml) {
		String expression = "href\\s*=\\s*(?:\"([^\"]*)\"|\'([^']*)'|([^\"\'>\\s]+))";
		Pattern p = Pattern.compile(expression);
		return p.matcher(paramHtml);
	}

	/**
	 * 匹配外链接内容
	 * 
	 * @param htmlBodyContent
	 * @return
	 */
	public static String getMatchLinkStr(String htmlBodyContent) {
		String hrefStr = htmlBodyContent;
		Matcher m = matchHrefGroup(htmlBodyContent);
		String matchStr = "http://";
		// String matchStr = "/ckb/,/ckb/knlgfile/,/javascript:,imgScr";
		String[] matchSplit = matchStr.split(",");
		while (m.find()) {
			String htmlStr = m.group();
			for (int i = 0; i < matchSplit.length; i++) {
				if (!htmlStr.contains(matchSplit[i]) || htmlStr.contains("/ckb/")) {
					continue;
				} else {
					String hrefRep = htmlStr.replace("href=", "").replace("\"", "").replace("'", "");
					hrefStr = hrefStr.replace(htmlStr, "id =\"web_" + (i + 1) + "\" onclick=\"openWeb('" + hrefRep
							+ "')\" style=\"cursor: pointer;\"");
				}
			}
			// System.out.println("修改前="+htmlStr);
		}
		return hrefStr;
	}

	/**
	 * 获取img元素中的src值
	 * 
	 * @param sourceStr
	 */
	public static String getMatchImgForSrc(String sourceStr) {
		String srcStr = "";
		Matcher m = Pattern.compile("src=\"?(.*?)(\"|>|\\s+)").matcher(sourceStr);
		while (m.find()) {
			srcStr = m.group(1);
		}
		return srcStr;
	}

	/**
	 * 匹配某内容的图片路径
	 * 
	 * @param sourceStr
	 */
	public static List<String> matchImgGetSrc(String sourceStr) {
		String img = "";
		Pattern p_image;
		Matcher m_image;
		List<String> pics = new ArrayList<String>();

		String regEx_img = "<img.*src\\s*=\\s*(.*?)[^>]*?>";
		p_image = Pattern.compile(regEx_img, Pattern.CASE_INSENSITIVE);
		m_image = p_image.matcher(sourceStr);
		while (m_image.find()) {
			img = img + "," + m_image.group();
			Matcher m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(img);
			while (m.find()) {
				pics.add(m.group(1));
			}
		}
		return pics;
	}

	/**
	 * 匹配某内容的图片路径(只返回一张图片)
	 * 
	 * @param sourceStr
	 */
	public static String matchOnlyImgGetSrc(String sourceStr) {
		String img = "";
		String matchOnlyImg = "";

		Pattern p_image;
		Matcher m_image;

		String regEx_img = "<img.*src\\s*=\\s*(.*?)[^>]*?>";
		p_image = Pattern.compile(regEx_img, Pattern.CASE_INSENSITIVE);
		m_image = p_image.matcher(sourceStr);
		while (m_image.find()) {
			img = img + "," + m_image.group();
			Matcher m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(img);
			while (m.find()) {
				matchOnlyImg = m.group(1);
				break;
			}
		}
		return matchOnlyImg;
	}

	/**
	 * 获取A标签
	 * 
	 * @param sourceStr
	 */
	public static String getMatchAReplace(String sourceStr) {
		String repStr = "";
		Matcher m = Pattern.compile("<a .*?>").matcher(sourceStr);
		while (m.find()) {
			String matchImgStr = m.group();
			sourceStr = sourceStr.replace(matchImgStr, "").replace("</a>", "");
			// repAStr = matchImgStr.replace("<", "&lt;").replace(">", "&gt;");
			// repStr += sourceStr.replace(matchImgStr,repAStr);
		}
		repStr = sourceStr;
		// repStr = isNullOrEmpty(repStr)?sourceStr:repStr;
		// System.out.println("repStr="+repStr);
		return repStr;
	}

	/**
	 * 获取img标签
	 * 
	 * @param sourceStr
	 */
	public static String getMatchImgReplaceNull(String sourceStr) {
		String repImgStr = "";
		Matcher m = Pattern.compile("<img .*?></img>").matcher(sourceStr);
		while (m.find()) {
			String matchImgStr = m.group();
			sourceStr = sourceStr.replace(matchImgStr, "");
		}
		repImgStr = sourceStr;
		// System.out.println("repImgStr="+repImgStr);
		return repImgStr;
	}

	/**
	 * 获取img标签
	 * 
	 * @param sourceStr
	 */
	public static String getMatchImgReplaceNull2(String sourceStr) {
		String repImgStr = "";
		Matcher m = Pattern.compile("<img .*?>").matcher(sourceStr);
		while (m.find()) {
			String matchImgStr = m.group();
			sourceStr = sourceStr.replace(matchImgStr, "");
		}
		repImgStr = sourceStr;
		// System.out.println("repImgStr="+repImgStr);
		return repImgStr;
	}

	/**
	 * 替换匹配自定义标签值为空字符
	 * 
	 * @param dryTag
	 * @param sourceStr
	 */
	public static String getMatchDryTagReplaceNull(String dryTag, String sourceStr) {
		String repImgStr = "";
		// <img .*?>
		Matcher m = Pattern.compile(dryTag).matcher(sourceStr);
		while (m.find()) {
			String matchImgStr = m.group();
			sourceStr = sourceStr.replace(matchImgStr, "");
		}
		repImgStr = sourceStr;
		// System.out.println("repImgStr="+repImgStr);
		return repImgStr;
	}

	/**
	 * 替换匹配自定义标签值为空字符 返回boolean值
	 * 
	 * @param dryTag
	 * @param sourceStr
	 */
	public static boolean getMatchDryTagReplaceIsBoolean(String dryTag, String sourceStr) {
		// <img .*?>
		sourceStr = sourceStr.replaceAll("\"", "").replaceAll("'", "");
		Matcher m = Pattern.compile(dryTag).matcher(sourceStr.toLowerCase());
		boolean isBoolean = m.matches();
		return isBoolean;
	}

	/**
	 * 获取图片链接集合
	 * 
	 * @param sourceStr
	 */
	public static List<Map<String, Object>> getMatchImgList(String sourceStr) {
		List<Map<String, Object>> imgList = new ArrayList<Map<String, Object>>();
		Matcher m = Pattern.compile("src=\"?(.*?)(\"|>|\\s+)").matcher(sourceStr);
		while (m.find()) {
			Map<String, Object> imgMap = new HashMap<String, Object>();
			String srcStr = m.group(1);
			imgMap.put("imgPath", srcStr);
			imgList.add(imgMap);
		}
		return imgList;
	}

	/**
	 * 获取img标签
	 * 
	 * @param sourceStr
	 */
	public static String getMatchImgConent(String sourceStr) {
		String srcStr = "";
		Matcher m = Pattern.compile("<img .*?>").matcher(sourceStr);
		while (m.find()) {
			String matchImgStr = m.group();
			srcStr += matchImgStr;
		}
		System.out.println("srcStr=" + srcStr);
		return srcStr;
	}

	/**
	 * 过滤重复数据
	 * 
	 * @param list
	 * @param columnName
	 * @param qryRowCount
	 * @param rtnRowCount
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static List filterRepeatList(List list, String columnName, int qryRowCount, int rtnRowCount) {
		int virtualCnt;
		int dataCnt = 0;
		Map hotMap = new HashMap();
		List hotList = new ArrayList();
		List<Map> tempList = new ArrayList();
		List<Map> newHotList = new ArrayList<Map>();
		do {
			virtualCnt = dataCnt; // foreach的起始坐标
			dataCnt += qryRowCount; // 预查的数量
			hotList.addAll(list);

			boolean flag;
			for (int i = virtualCnt; i < hotList.size(); i++) {
				hotMap = (Map) hotList.get(i);
				tempList = newHotList;
				flag = true;
				if (tempList.size() == 0) {
					newHotList.add(hotMap);
				} else {
					// 过滤重复数据
					for (int j = 0; j < tempList.size(); j++) {
						if (i == j)
							continue;
						// if(hotMap.get(columnName).equals(((Map)tempList.get(j)).get(columnName))){

						String ques1 = String.valueOf(hotMap.get(columnName));
						ques1 = ques1.replace("？", "").replace("?", "");
						String ques2 = String.valueOf(((Map) tempList.get(j)).get(columnName));
						ques2 = ques2.replace("？", "").replace("?", "");
						if (ques1.equals(ques2)) {
							flag = false;
							break;
						}
					}
					if (flag) {
						newHotList.add(hotMap);
					}
				}
				if (newHotList.size() == rtnRowCount)
					break;
			}
			if (hotList.size() < rtnRowCount
					|| (hotList.size() >= rtnRowCount && newHotList.size() < rtnRowCount && dataCnt >= qryRowCount * 5))
				break;
		} while (newHotList.size() < rtnRowCount); // 当经过相同问题筛选过后还不足10条问题则再重新向数据库拿一次做筛选
		return newHotList;
	}

	/**
	 * 返回sql语句对应的值
	 * 
	 * @param paramValList
	 * @param columnsName
	 * @param columnsName1
	 * @param columnsNam2
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static String getKeyForValue(List paramValList, String columnsName, String columnsName1,
			String columnsNam2) {
		StringBuffer decodeStr = new StringBuffer();
		decodeStr.append("DECODE(").append(columnsName).append(",");
		if (paramValList != null && paramValList.size() > 0) {
			int n = paramValList.size();
			for (int i = 0; i < paramValList.size(); i++) {
				Map map = (Map) paramValList.get(i);
				String key = String.valueOf(map.get(columnsName1));
				String value = String.valueOf(map.get(columnsNam2));
				decodeStr.append("'").append(key).append("',").append("'").append(value).append("'");
				if (i != (n - 1)) {
					decodeStr.append(",");
				}
			}
		}
		decodeStr.append(") AS KEY_FOR_VALUE ");
		return decodeStr.toString();
	}

	/**
	 * 返回sql语句对应的值
	 * 
	 * @param paramValList
	 * @param columnsName
	 * @param columnsName1
	 * @param columnsNam2
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static String getKeyForValue(List paramValList, String columnsName, String columnsName1, String columnsNam2,
			String asName, boolean isNum) {
		StringBuffer decodeStr = new StringBuffer();
		decodeStr.append("DECODE(").append(columnsName).append(",");
		if (paramValList != null && paramValList.size() > 0) {
			int n = paramValList.size();
			for (int i = 0; i < paramValList.size(); i++) {
				Map map = (Map) paramValList.get(i);
				String key = String.valueOf(map.get(columnsName1));
				String value = String.valueOf(map.get(columnsNam2));
				if (isNum) {
					decodeStr.append("'").append(key).append("',").append(value).append("");
				} else {
					decodeStr.append("'").append(key).append("','").append(value).append("'");
				}
				if (i != (n - 1)) {
					decodeStr.append(",");
				}
			}
		}
		decodeStr.append(") AS ").append(asName);
		return decodeStr.toString();
	}

	/**
	 * 知识点内容页部分图片href链接
	 * 
	 * @param htmlBodyContent
	 * @return
	 */
	public static String getMatchImgHrefStr(String htmlBodyContent) {
		String hrefStr = htmlBodyContent;
		Matcher m = matchHrefGroup(htmlBodyContent);
		String matchStr = "http://";
		// String matchStr = "/ckb/,/ckb/knlgfile/,/javascript:,imgScr";
		String[] matchSplit = matchStr.split(",");
		while (m.find()) {
			String htmlStr = m.group();
			for (int i = 0; i < matchSplit.length; i++) {
				if (!htmlStr.contains(matchSplit[i]) || htmlStr.contains("/ckb/")) {
					continue;
				} else {
					String hrefRep = htmlStr.replace("href=", "").replace("\"", "").replace("'", "");
					hrefStr = hrefStr.replace(htmlStr, "id =\"web_" + (i + 1) + "\" onclick=\"openWeb('" + hrefRep
							+ "')\" style=\"cursor: pointer;\"");
				}
			}
			// System.out.println("修改前="+htmlStr);
		}
		return hrefStr;
	}

	/**
	 * 返回字典表中排序方式
	 * 
	 * @param list
	 * @param columnsName
	 * @param dictValue
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static String getDecodeVisorder(List paramValList, String columnsName, String columnsName1,
			String columnsNam2) {
		StringBuffer str = new StringBuffer();
		str.append("DECODE(").append(columnsName).append(",");
		if (paramValList != null && paramValList.size() > 0) {
			int n = paramValList.size();
			for (int i = 0; i < paramValList.size(); i++) {
				Map map = (Map) paramValList.get(i);
				String key = String.valueOf(map.get(columnsName1));
				String value = String.valueOf(map.get(columnsNam2));
				str.append("'").append(key).append("',").append(value);
				if (i != (n - 1)) {
					str.append(",");
				}
			}
			str.append(") AS DECODE_VISORDER ");
		}
		String decodeVisorder = str.toString();
		return decodeVisorder;
	}

	/**
	 * 返回字典表中对应key的转换值
	 * 
	 * @param list
	 * @param columnsName
	 * @param dictType
	 * @param dictValue
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static String getDecodeToKeyValue(List list, String columnsName, String dictType, String dictValue) {
		String decodeKeyVal = getKeyForValue(list, columnsName, dictType, dictValue);
		return decodeKeyVal;
	}

	/**
	 * 两个时间相差距离多少天多少小时多少分多少秒
	 * 
	 * @param str1
	 *            时间参数 1 格式：1990-01-01 12:00:00
	 * @param str2
	 *            时间参数 2 格式：2009-01-01 12:00:00
	 * @return String 返回值为：xx天xx小时xx分xx秒
	 */
	public static String getDistanceTimeForHtmlSpan(String str1, String str2) {
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date one;
		Date two;
		long day = 0;
		long hour = 0;
		long min = 0;
		long sec = 0;
		try {
			one = df.parse(str1);
			two = df.parse(str2);
			long time1 = one.getTime();
			long time2 = two.getTime();
			long diff;
			if (time1 < time2) {
				diff = time2 - time1;
			} else {
				diff = time1 - time2;
			}
			day = diff / (24 * 60 * 60 * 1000);
			hour = (diff / (60 * 60 * 1000) - day * 24);
			min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
			sec = (diff / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		String spanDayStr = "";
		String spanHourStr = "";
		String spanMinStr = "";
		String spanSecStr = "";
		if (day > 0) {
			spanDayStr = "<span>" + day + "</span>" + "天";
		}
		if (hour > 0) {
			spanHourStr = "<span>" + hour + "</span>" + "小时";
		}
		if (min > 0) {
			spanMinStr = "<span>" + min + "</span>" + "分";
		}
		if (sec > 0) {
			spanSecStr = "<span>" + sec + "</span>" + "秒";
		}
		String dayMsg = spanDayStr + spanHourStr + spanMinStr + spanSecStr;
		// System.out.println(dayMsg);
		return dayMsg;
	}

	/**
	 * 两个时间相差距离多少天多少小时多少分多少秒
	 * 
	 * @param str1
	 *            时间参数 1 格式：1990-01-01 12:00:00
	 * @param str2
	 *            时间参数 2 格式：2009-01-01 12:00:00
	 * @return String 返回值为：xx天xx小时xx分xx秒
	 */
	public static String getDistanceTime(String str1, String str2) {
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date one;
		Date two;
		long day = 0;
		long hour = 0;
		long min = 0;
		long sec = 0;
		try {
			one = df.parse(str1);
			two = df.parse(str2);
			long time1 = one.getTime();
			long time2 = two.getTime();
			long diff;
			if (time1 < time2) {
				diff = time2 - time1;
			} else {
				diff = time1 - time2;
			}
			day = diff / (24 * 60 * 60 * 1000);
			hour = (diff / (60 * 60 * 1000) - day * 24);
			min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
			sec = (diff / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		String dayMsg = day + "天" + hour + "小时" + min + "分" + sec + "秒";
		System.out.println(dayMsg);
		return dayMsg;
	}

	/**
	 * 获取当前日期星期几
	 * 
	 * @param date
	 * @return
	 */
	public static String getWeekOfDate(Date date) {
		String[] weekDays = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);

		int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
		if (w < 0) {
			w = 0;
		}
		System.out.println(weekDays[w]);
		return weekDays[w];
	}

	// 用来全局控制 上一周，本周，下一周的周数变化
	private static int weeks = 0;

	// 获得当前日期与本周一相差的天数
	private static int getMondayPlus() {
		Calendar cd = Calendar.getInstance();
		// 获得今天是一周的第几天，星期日是第一天，星期二是第二天......
		int dayOfWeek = cd.get(Calendar.DAY_OF_WEEK);
		if (dayOfWeek == 1) {
			return -6;
		} else {
			return 2 - dayOfWeek;
		}
	}

	// 获得上周星期一的日期
	public String getPreviousMonday() {
		weeks--;
		int mondayPlus = getMondayPlus();
		GregorianCalendar currentDate = new GregorianCalendar();
		currentDate.add(GregorianCalendar.DATE, mondayPlus + 7 * weeks);
		Date monday = currentDate.getTime();
		DateFormat df = DateFormat.getDateInstance();
		String preMonday = df.format(monday);
		return preMonday;
	}

	/**
	 * 获得上周星期一的日期
	 * 
	 * @return
	 */
	public String getCurrentMonday() {
		weeks = 0;
		int mondayPlus = getMondayPlus();
		GregorianCalendar currentDate = new GregorianCalendar();
		currentDate.add(GregorianCalendar.DATE, mondayPlus);
		Date monday = currentDate.getTime();
		DateFormat df = DateFormat.getDateInstance();
		String preMonday = df.format(monday);
		return preMonday;
	}

	/**
	 * 获得上周星期一的日期
	 * 
	 * @return
	 */
	public String getNextMonday() {
		weeks++;
		int mondayPlus = getMondayPlus();
		GregorianCalendar currentDate = new GregorianCalendar();
		currentDate.add(GregorianCalendar.DATE, mondayPlus + 7 * weeks);
		Date monday = currentDate.getTime();
		DateFormat df = DateFormat.getDateInstance();
		String preMonday = df.format(monday);
		return preMonday;
	}

	/**
	 * 获得相应周的周四的日期
	 * 
	 * @return
	 */
	public static String getThursday() {
		int mondayPlus = getMondayPlus();
		GregorianCalendar currentDate = new GregorianCalendar();
		currentDate.add(GregorianCalendar.DATE, mondayPlus + 7 * weeks + 10);
		Date monday = currentDate.getTime();
		DateFormat df = DateFormat.getDateInstance();
		String preMonday = df.format(monday);
		return preMonday;
	}

	/**
	 * 验证是否为数字
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isNumericForStr(String str) {
		Pattern pattern = Pattern.compile("[0-9]*");
		Matcher isNum = pattern.matcher(str);
		if (!isNum.matches()) {
			return false;
		}
		return true;
	}

	/**
	 * 获取随机数
	 * 
	 * @param rownum
	 *            参数说明:生成的位数
	 * @return
	 */
	public static String getRandomCode(int rownum) {
		Random r = new Random();
		Double d = r.nextDouble();
		System.out.println(d);
		String random = d + "";
		random = random.substring(3, 3 + rownum);
		System.out.println(random);
		return random;
	}

	/**
	 * 返回指定数字范围内随机数
	 * 
	 * @param rownum
	 *            参数说明:指定数字范围
	 * @return
	 */
	public static int getRandomNumber(int rownum) {
		int randomInt = new Random().nextInt(rownum);
		return randomInt;
	}

	/**
	 * 递归调用随机数(保证不重复)
	 * 
	 * @param paramRownum
	 *            参数说明:指定数值
	 * @param rownum
	 *            参数说明:指定数字范围
	 * @return
	 */
	public static int randomNumber(int paramRownum, int rownum) {
		if (paramRownum < 1) {
			return 1;
		}
		int randomPage = 1;
		rownum = rownum < 1 ? 1 : rownum;
		// 获取指定数字范围内随机数
		int randomNumber = new Random().nextInt(rownum);
		// 判断指定数字范围内随机数与指定数值是否相等,如果相等,则重新获取
		if (randomNumber == paramRownum || randomNumber == 0) {
			if (rownum <= 1) {
			} else {
				randomNumber(paramRownum, rownum);
			}
		} else {
			randomPage = randomNumber;
		}
		randomPage = randomPage < 1 ? 1 : randomPage;
		return randomPage;
	}

	/**
	 * 格式化SQL语句IN字符串格式
	 * 
	 * @param isAdd
	 *            参数说明:是否添加分号
	 * @param paramVal
	 * @return
	 */
	public static String getStringInFormat(boolean isAdd, String paramVal) {
		String type = "";
		if (isAdd) {
			type = "'";
		}
		StringBuffer sqlInStr = new StringBuffer();
		if (!isNullOrEmpty(paramVal)) {
			if (paramVal.indexOf(",") != -1) {
				String[] paramValArray = paramVal.split(",");
				int n = paramValArray.length;
				for (int i = 0; i < paramValArray.length; i++) {
					sqlInStr.append(type).append(paramValArray[i]).append(type);
					if (i != (n - 1)) {
						sqlInStr.append(",");
					}
				}
			} else {
				sqlInStr.append("'").append(paramVal).append("'");
			}
		}
		return sqlInStr.toString();
	}

	/**
	 * 格式化SQL语句IN字符串格式
	 * 
	 * @param isAdd
	 *            参数说明:是否添加分号
	 * @param object
	 *            参数说明:对象参数
	 * @param splitStr
	 *            参数说明:分割字符
	 * @return
	 */
	public static String getStringInFormat(boolean isAdd, Object object, String splitStr) {
		String type = "";
		if (isAdd) {
			type = "'";
		}
		StringBuffer sqlInStr = new StringBuffer();
		if (object instanceof String) {
			String paramVal = (String) object;
			if (!isNullOrEmpty(paramVal)) {
				if (paramVal.indexOf(",") != -1) {
					String[] paramValArray = paramVal.split(splitStr);
					int n = paramValArray.length;
					for (int i = 0; i < paramValArray.length; i++) {
						sqlInStr.append(type).append(paramValArray[i]).append(type);
						if (i != (n - 1)) {
							sqlInStr.append(",");
						}
					}
				} else {
					sqlInStr.append("'").append(paramVal).append("'");
				}
			}
		} else if (object instanceof String[]) {
			String[] paramVal = (String[]) object;
			if (paramVal != null) {
				int n = paramVal.length;
				for (int i = 0; i < paramVal.length; i++) {
					sqlInStr.append(type).append(paramVal[i]).append(type);
					if (i != (n - 1)) {
						sqlInStr.append(",");
					}
				}
			}
		}
		return sqlInStr.toString();
	}

	/**
	 * 格式化SQL语句IN字符串格式
	 * 
	 * @param isAdd
	 *            参数说明:是否添加分号
	 * @param paramVal
	 * @return
	 */
	public static String getStringArrayFormat(boolean isAdd, String[] paramVal) {
		String type = "";
		if (isAdd) {
			type = "'";
		}
		StringBuffer sqlInStr = new StringBuffer();
		if (paramVal != null) {
			int n = paramVal.length;
			for (int i = 0; i < paramVal.length; i++) {
				sqlInStr.append(type).append(paramVal[i]).append(type);
				if (i != (n - 1)) {
					sqlInStr.append(",");
				}
			}
		}
		return sqlInStr.toString();
	}

	/**
	 * 拼装标签筛选条件语句(循环方式拼装) 1234(属性值)_954(属性组),1275_954
	 * 
	 * @param whereName
	 *            参数说明:WHERE条件语句
	 * @param endBracketStr
	 *            参数说明:结束括号语句
	 * @return
	 */
	public static String getTagFilterForWhereSql(Map<String, Object> paramMap, String whereName, String endBracketStr) {
		StringBuffer whereSql = new StringBuffer();
		String tagFilter = getValueForKey("tagFilter", paramMap);
		if (!isNullOrEmpty(tagFilter)) {
			String[] tagFilters = tagFilter.split(",");
			for (int i = 0; i < tagFilters.length; i++) {
				whereSql.append(whereName).append("(");
				String[] pGroups = tagFilters[i].split("_");
				String propertyId = pGroups[0];
				whereSql.append("'").append(propertyId).append("'").append(endBracketStr);
			}
		}
		return whereSql.toString();
	}

	/**
	 * 生成一个格式为"yyyyMMddhhmmss"的字符串
	 * 
	 * @author ajm
	 * @return
	 */
	public static String makeDateDirName() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		// 转换为字符串
		String formatDate = sdf.format(new Date());
		return formatDate;
	}

	/**
	 * 生成一个格式为"yyyyMMdd"的字符串
	 * 
	 * @author ajm
	 * @return
	 */
	public static String makeDateDirName2() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		// 转换为字符串
		String formatDate = sdf.format(new Date());
		return formatDate;
	}

	/**
	 * 论坛字符串转译
	 * 
	 * @author ajm
	 * @return
	 */
	public static String getStrByTranslation(String strContent) {
		// 替换转译字符
		String str = strContent;
		str = str.replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll("&quot;", "\"");
		str = str.replaceAll("<p><br></p>", "");
		str = matchTagAForStr(str);
		return str;
	}

	/**
	 * list格式化为字符串
	 * 
	 * @param paramVal
	 * @param columnsName
	 * @return
	 */
	public static String ListToString(List<Map<String, Object>> list, String columnsName) {
		StringBuffer str = new StringBuffer();
		if (list != null && list.size() > 0) {
			int n = list.size();
			for (int i = 0; i < list.size(); i++) {
				Map<String, Object> map = (Map<String, Object>) list.get(i);
				str.append(getValueForKey(columnsName, map));
				if (i != (n - 1)) {
					str.append(",");
				}
			}
		}
		return str.toString();
	}

	/**
	 * list格式化为字符串
	 * 
	 * @param list
	 *            参数说明:数据集合
	 * @param columnsName
	 *            参数说明:字段名称
	 * @param symbol
	 *            参数说明:分隔符
	 * @return
	 */
	public static String ListToString(List<Map<String, Object>> list, String columnsName, String symbol) {
		StringBuffer str = new StringBuffer();
		if (list != null && list.size() > 0) {
			int n = list.size();
			for (int i = 0; i < list.size(); i++) {
				Map<String, Object> map = (Map<String, Object>) list.get(i);
				str.append(getValueForKey(columnsName, map));
				if (i != (n - 1)) {
					str.append(symbol);
				}
			}
		}
		return str.toString();
	}

	/**
	 * list格式化为字符串
	 * 
	 * @param list
	 *            参数说明:数据集合
	 * @param columnsName
	 *            参数说明:字段名称
	 * @param symbol
	 *            参数说明:分隔符
	 * @param isQuotes
	 *            参数说明:引号等符号
	 * @return
	 */
	public static String ListToString(List<Map<String, Object>> list, String columnsName, String symbol,
			String isQuotes) {
		StringBuffer str = new StringBuffer();
		if (list != null && list.size() > 0) {
			int n = list.size();
			for (int i = 0; i < list.size(); i++) {
				Map<String, Object> map = (Map<String, Object>) list.get(i);
				if (isNullOrEmpty(isQuotes)) {
					str.append(getValueForKey(columnsName, map));
				} else {
					str.append(isQuotes).append(getValueForKey(columnsName, map)).append(isQuotes);
				}
				if (i != (n - 1)) {
					str.append(symbol);
				}
			}
		}
		return str.toString();
	}

	/**
	 * 数组格式化为字符串
	 * 
	 * @param isQuotes
	 * @param arrayStr
	 * @return
	 */
	public static String arrayToString(boolean isQuotes, String arrayStr) {
		StringBuffer str = new StringBuffer();
		if (!isNullOrEmpty(arrayStr)) {
			String[] array = arrayStr.split(",");
			int n = array.length;
			for (int i = 0; i < array.length; i++) {
				if (!isQuotes) {
					str.append(array[i]);
				} else {
					str.append("'").append(array[i]).append("'");
				}
				if (i != (n - 1)) {
					str.append(",");
				}
			}
		}
		return str.toString();
	}

	/**
	 * 格式化手机号码
	 * 
	 * @param phone
	 * @return
	 */
	public static String getPhoneFormat(String phone) {
		String phoneFormat = phone.substring(0, 3) + "********";
		try {
			String phoneFormatStr = phone.trim();
			String phoneFormat1 = phoneFormatStr.substring(0, 3);
			String phoneFormat2 = phoneFormatStr.substring(7);
			phoneFormat = phoneFormat1 + "***" + phoneFormat2;
		} catch (Exception e) {
			phoneFormat = phone.substring(0, 3) + "********";
			e.printStackTrace();
		}
		return phoneFormat;
	}

	/**
	 * 解析Ascii码(十进制)
	 * 
	 * @param str
	 *            字符串
	 * @param separate
	 *            分隔符
	 * @return
	 */
	public static String[] getImDecodeAscii(String str, String separate) {
		// String s = "bvjtwhtywr6527|17724319|20150702152801";// 字符串

		// char[] chars = s.toCharArray(); // 把字符中转换为字符数组

		// StringBuffer str = new StringBuffer();
		// System.out.println("\n\n汉字 ASCII\n----------------------");
		// int index = 0;
		// for (int i = 0; i < chars.length; i++) {// 输出结果
		// index = index+1;
		// int charsInt = (int) chars[i];
		// if(index%2==0){
		// charsInt = ((int) chars[i]-5);
		// }
		// str.append((char)charsInt);
		// }

		String strs = str.toString();
		StringBuffer str1 = new StringBuffer();
		StringBuffer outPut = new StringBuffer();
		char[] chars1 = strs.toCharArray(); // 把字符中转换为字符数组
		for (int j = 0; j < chars1.length; j++) {// 输出结果
			int charsInt = (int) chars1[j];
			str1.append((char) charsInt);
			// System.out.print((char)charsInt);
		}

		// System.out.println();

		String strs1 = str1.toString();
		int index1 = 0;
		char[] chars2 = strs1.toCharArray(); // 把字符中转换为字符数组
		for (int k = 0; k < chars2.length; k++) {// 输出结果
			index1 = index1 + 1;
			int charsInt = (int) chars2[k];
			if (index1 % 2 == 0) {
				charsInt = ((int) chars2[k] + 5);
			}
			outPut.append((char) charsInt);
			// System.out.print((char)charsInt);
		}
		return outPut.toString().split(separate);
	}

	/**
	 * 脱敏处理：粉丝中心
	 * 
	 * @param type
	 *            <p>
	 * 			1：业务号码（*从后数起4~7位）
	 *            <p>
	 * 			2：姓名/昵称（小于3位就*最后一位，等于大于3位就*倒数第二位）
	 *            <p>
	 * 			3：多媒体账号（*从后数起3~4位）
	 * @author yangli : 2015-7-7
	 */
	public static String getHiddenStr(int type, String str) {
		String s = "";
		try {
			if (!isEmpty(str)) {
				int lg = str.length();
				// 业务号码
				if (type == 1) {
					char[] cs = str.toCharArray();
					for (int c = 0; c < cs.length; c++) {
						if (c < 3) {
							s += cs[c];
						} else if (c >= 3 && c < 7) {
							s += "*";
						} else {
							s += cs[c];
						}
					}
				} else if (type == 2) {// 姓名、昵称
					if (lg == 1) {
						s = str;
					} else if (lg > 1 && lg < 3) {
						s = str.substring(0, lg - 1) + "*";
					} else { // >= 3
						s = str.substring(0, lg - 2) + "*" + str.substring(lg - 1, lg);
					}
				}
			}
		} catch (Exception e) {
			s = str;
		}
		return s;
	}

	/**
	 * 保留小数
	 * 
	 * @param in
	 * @param format
	 * @return
	 */
	public static String doubleFormat(double in, String format) {
		DecimalFormat df = new DecimalFormat(format);
		return df.format(in);
	}

	public static final String ALLCHAR = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!~@#$%^&*()_|";

	/**
	 * 返回一个定长的随机字符串(只包含大小写字母、数字、特殊字符)
	 * 
	 * @param length
	 *            随机字符串长度
	 * @return 随机字符串
	 */
	public static String generateString(int length) {
		StringBuffer sb = new StringBuffer();
		Random random = new Random();
		for (int i = 0; i < length; i++) {
			sb.append(ALLCHAR.charAt(random.nextInt(ALLCHAR.length())));
		}
		System.out.println("只包含大小写字母、数字、特殊字符=" + sb.toString());
		return sb.toString();
	}

	/**
	 * 获取img标签
	 * 
	 * @param sourceStr
	 */
	public static String getMatchReplaceTargetContentImgConent(String sourceStr, String regex, String targetCont) {
		// String regex="src=\"(http)s?://(.*?):(\\d*)";
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(sourceStr);
		while (m.find()) {
			sourceStr = sourceStr.replaceAll(m.group(), targetCont);
		}
		return sourceStr;
	}

	/**
	 * 提取内容中所有A标签完整内容,同时替换A标签指定内容
	 * 
	 * @param sourceStr
	 * @return
	 */
	// @Test
	public static String matchTagAForStr(String sourceStr) {
		String str = sourceStr;
		// str = "<p>65456465<br/></p><p><a href=\"http://www.ddio.com\"
		// _src=\"http://www.ddio.com\">http://www.ddio.com</a>
		// </p><p>5445</p>";
		// 提取内容中所有A标签完整数据
		Matcher m1 = Pattern.compile("<a[^>]*>(.*?)</a>").matcher(str);
		// 提取a标签中的内容
		Matcher m2 = Pattern.compile("<a[^>]*>([^<]*)</a>").matcher(str);

		StringBuffer allTagAContStr = new StringBuffer();
		while (m1.find()) {
			String allTagACont = m1.group();
			allTagAContStr.append(allTagACont).append(",");
			// System.out.println("allTagACont="+allTagACont);
		}
		StringBuffer matchTagAStr = new StringBuffer();
		while (m2.find()) {
			String matchTagACont = m2.group(1);
			matchTagAStr.append(matchTagACont).append(",");
			// System.out.println("matchTagAStr="+matchTagAStr);
		}

		// System.out.println("allTagAContStr="+allTagAContStr.toString());
		// System.out.println("matchTagAStr="+matchTagAStr.toString());

		String[] allTagAConts = allTagAContStr.toString().split(",");
		String[] matchTagAConts = matchTagAStr.toString().split(",");
		for (int i = 0; i < allTagAConts.length; i++) {
			if (isNullOrEmpty(allTagAConts[i]) || isNullOrEmpty(matchTagAConts[i])) {
				continue;
			}
			str = str.replace(allTagAConts[i], matchTagAConts[i]);
		}

		Matcher m3 = Pattern.compile("<a .*?>").matcher(str);
		Matcher m4 = Pattern.compile("<a[^>]*>([^<]*)").matcher(str);
		StringBuffer allTagAContStr3 = new StringBuffer();
		while (m3.find()) {
			String allTagACont3 = m3.group();
			allTagAContStr3.append(allTagACont3).append(",");
			// System.out.println("matchTagAStr="+matchTagAStr);
		}
		StringBuffer matchTagAStr4 = new StringBuffer();
		while (m4.find()) {
			String matchTagACont4 = m4.group(1);
			matchTagAStr4.append(matchTagACont4).append(",");
			// System.out.println("matchTagAStr="+matchTagAStr);
		}
		// System.out.println("=============================================");

		// System.out.println("allTagAContStr3="+allTagAContStr3.toString());
		// System.out.println("matchTagAStr4="+matchTagAStr4.toString());

		String[] allTagAConts3 = allTagAContStr3.toString().split(",");
		String[] matchTagAConts4 = matchTagAStr4.toString().split(",");
		for (int i = 0; i < allTagAConts3.length; i++) {
			if (isNullOrEmpty(allTagAConts3[i]) || isNullOrEmpty(matchTagAConts4[i])) {
				continue;
			}
			str = str.replace(allTagAConts3[i], matchTagAConts4[i]);
		}
		str = str.replace("<a ", "<p ").replace("</a>", "</p>");
		// System.out.println("str="+str);
		return str;
	}

	/**
	 * 拆分关键字,拆分为每N个为一组
	 * 
	 * @param keywordName
	 *            参数说明:关键字
	 * @param groupNum
	 *            参数说明:分组数
	 * @return
	 */
	public static String getGroupNameForKeywordName(String keywordName, int groupNum) {
		String delimiter = ",";
		String keywordNameStr = keywordName;
		keywordName = keywordName.replace("，", "").replace(",", "").replace("？", "").replace("?", "").replace("、", "")
				.replace("/", "").replace("、", "").replace("“”", "").replace("'", "");
		if (keywordNameStr.length() > 4) {
			keywordNameStr = getGroupStr(keywordName, delimiter, groupNum);
		} else {
			// groupNum = 2;
			keywordNameStr = getGroupStr(keywordName, delimiter, groupNum);
		}
		// System.out.println(keywordNameStr);
		return keywordNameStr;
	}

	/**
	 * 验证请求的host名称是否与dict表的host名称匹配 HOST名称(用于过滤host头部攻击)
	 * 
	 * @param hostName
	 * @param dictHostName
	 * @return
	 */
	public static boolean isEqualsHostName(String hostName, String dictHostName) {
		boolean isEqualsHostName = false;
		// HOST名称(用于过滤host头部攻击)
		String[] dictHostNames = dictHostName.split(",");
		for (int i = 0; i < dictHostNames.length; i++) {
			if (dictHostNames[i].equals(hostName)) {
				isEqualsHostName = true;
				break;
			}
		}
		return isEqualsHostName;
	}

	/**
	 * 随机生成数 格式:46950bd7-7e05-4917-8260-6417d4a5eb75
	 * 
	 * @param index
	 *            参数说明:截取下标
	 * @return
	 */
	public static String randUuid(int index) {
		int count = 0;
		int existCount = 3;
		String randUuidNum = "";
		String uuidKey = Constants.UUID_KEY.substring(0, index);
		String uuid = UUID.randomUUID().toString();
		String[] uuidArray = uuid.split("-");
		for (String uuidStr : uuidArray) {
			if (count == existCount) {
				index++;
			}
			String uuidSub = uuidStr.substring(0, index);
			if (count == existCount) {
				randUuid(index);
			}
			if (uuidSub.equals(uuidKey)) {
				count++;
				continue;
			} else {
				randUuidNum = uuidSub;
				break;
			}
		}
		return randUuidNum;
	}

	/**
	 * 查询字符串中判断某个字符串出现的次数
	 * 
	 * @param str
	 * @param targetStr
	 */
	public static boolean getStringFindTargetStrCount(String str, String targetStr, int maxCount) {
		int count = 0;
		boolean isFlag = true;
		// 遍历数组的每个元素
		for (int i = 0; i <= str.length() - 1; i++) {
			String getstr = str.substring(i, i + 1);
			if (getstr.equals(targetStr)) {
				count++;
			}
		}
		if (count > 0 && count > maxCount) {
			isFlag = false;
		}
		// System.out.println("getStringFindTargetStrCount="+isFlag);
		return isFlag;
	}

	/**
	 * 随机生成字符，含大写、小写、数字 <b>function:</b> 功能
	 * 
	 * @createDate 2010-8-23 上午10:33:55
	 * @author hoojo
	 * @return
	 */
	public static String getRandomChar() {
		int index = (int) Math.round(Math.random() * 2);
		String randChar = "";
		switch (index) {
		case 0:// 大写字符
			randChar = String.valueOf((char) Math.round(Math.random() * 25 + 65));
			break;
		case 1:// 小写字符
			randChar = String.valueOf((char) Math.round(Math.random() * 25 + 97));
			break;
		default:// 数字
			randChar = String.valueOf(Math.round(Math.random() * 9));
			break;
		}
		return randChar;
	}

	/**
	 * <b>function:</b> 随机生成字体、文字大小
	 * 
	 * @createDate 2010-8-23 上午10:44:22
	 * @author hoojo
	 * @return
	 */
	public static Font getRandomFont() {
		String[] fonts = { "Georgia", "Verdana", "Arial", "Tahoma", "Time News Roman", "Courier New", "Arial Black",
				"Quantzite" };
		int fontIndex = (int) Math.round(Math.random() * (fonts.length - 1));
		int fontSize = (int) Math.round(Math.random() * 4 + 16);
		return new Font(fonts[fontIndex], Font.PLAIN, fontSize);
	}

	/**
	 * 对字符串ascii编码
	 * 
	 * @param encodeStr
	 * @return
	 */
	public static String encodeAscii(String encodeStr) {
		int index = 0;
		StringBuffer outPut = new StringBuffer();
		// System.out.println("encodeStr="+encodeStr);
		// 把字符中转换为字符数组
		char[] chars = encodeStr.toCharArray();
		for (int k = 0; k < chars.length; k++) {
			index = index + 1;
			int charsInt = (int) chars[k];
			if (index % 2 == 0) {
				charsInt = ((int) chars[k] + 5);
				// System.out.println("chars[k]="+chars[k]+"---charsInt="+charsInt+"--->(char)charsInt="+(char)charsInt);
			}
			outPut.append((char) charsInt);
		}
		return outPut.toString();
	}

	/**
	 * 对字符串ascii解码
	 * 
	 * @param encodeStr
	 * @return
	 */
	public static String decodeAscii(String encodeStr) {
		int index = 0;
		StringBuffer outPut = new StringBuffer();
		// 把字符中转换为字符数组
		char[] chars = encodeStr.toString().toCharArray();
		System.out.println("汉字 ASCII\n----------------------");
		for (int i = 0; i < chars.length; i++) {
			index = index + 1;
			int charsInt = (int) chars[i];
			if (index % 2 == 0) {
				charsInt = ((int) chars[i] - 5);
			}
			outPut.append((char) charsInt);
		}
		return outPut.toString();
	}

	/**
	 * 随机生成电信号码开头前3位
	 * 
	 * @return
	 */
	public static String dianxinSuffix() {
		String[] dianxinSuffix = new String[] { "133", "153", "173", "177", "180", "181", "189" };
		int randomInt = new Random().nextInt(dianxinSuffix.length);
		return dianxinSuffix[randomInt];
	}

	/**
	 * 随机生成其中一个数据
	 * 
	 * @return
	 */
	public static String getRandomOnlyOne(String[] params) {
		int randomInt = new Random().nextInt(params.length);
		return params[randomInt];
	}

	/**
	 * 随机生成字符串
	 * 
	 * @param base		指定生成的字符串
	 * @param length	指定生成的长度
	 * @return
	 */
	public static String getRandomString(String base, int length) {
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < length; i++) {
			int number = random.nextInt(base.length());
			sb.append(base.charAt(number));
		}
		return sb.toString();
	}

	/**
	 * 获取去掉横线的长度为32的UUID串.
	 * 
	 * @return uuid.
	 */
	public static String get32UUID() {
		return UUID.randomUUID().toString().replace("-", "");
	}

	/**
	 * 获取带横线的长度为36的UUID串.
	 * 
	 * @return uuid.
	 */
	public static String get36UUID() {
		return UUID.randomUUID().toString();
	}
	
	/**
	 * 解析出url参数中的键值对
	 * 如 "index.jsp?Action=del&id=123"，解析出Action:del,id:123存入map中
	 * 
	 * @param url 参数说明：url地址
	 * @return url请求参数部分
	 */
	public static Map<String,Object> urlParamToMap(String url){
		Map<String,Object> paramMap = new HashMap<String,Object>();
		if(!StringUtils.isNullOrEmpty(url)){
			if(url.indexOf("?")!=-1){
				String arrSplit = url.substring(url.indexOf("?")+1);
				if(arrSplit.indexOf("&")!=-1){
					for(String strSplit : arrSplit.split("&")){
						String[] arrSplitEqual = strSplit.split("=");
						paramMap.put(arrSplitEqual[0], arrSplitEqual[1]);
					}
				}else{
					String[] arrSplitEqual = arrSplit.split("=");
					paramMap.put(arrSplitEqual[0], arrSplitEqual[1]);
				}
			}
		}
		return paramMap;
	}
	
	/**
	 * 判断是否为json格式
	 * @param str
	 * @return
	 */
	public static boolean isJsonFormat(String str){
		if(StringUtils.isNullOrEmpty(str)){
			return false;
		}else{
			final char[] strChar = str.substring(0, 1).toCharArray();
	        final char firstChar = strChar[0];
	        if(firstChar == '{' || firstChar == '['){
	            return true;
	        }else{
	            return false;
	        }
		}
	}
	
	/**
	 * 获取json格式为字符串或数组
	 * @param str
	 * @return
	 */
	public static String getJsonType(String str){
		if(!StringUtils.isJsonFormat(str)){
			return "";
		}else{
			final char[] strChar = str.substring(0, 1).toCharArray();
	        final char firstChar = strChar[0];
	        if(firstChar == '{' || firstChar == '['){
	        	return Constants.JSON_STRING;
	        } else {
	        	return Constants.JSON_ARRAY;
	        }
		}
	}
	
	/**
	 * 替换指定字符并返回处理后结果
	 * @param strVal
	 * @return
	 */
	public static String getReplaceStr(String strVal){
		if(!StringUtils.isNullOrEmpty(strVal)){
			if(Constants.REPLACE_HENG_STR.equals(strVal)){
				strVal = strVal.replace(Constants.REPLACE_HENG_STR, "");
				return strVal;
			}
		}
		return strVal;
	}
	
	/**
	 * 处理金额数据
	 * @param fundedAmount
	 * @return
	 */
	public static String formatFundedAmount(String fundedAmount){
		if(fundedAmount.indexOf(".")==-1) {
			if(fundedAmount.length()>=1 && fundedAmount.length()<3) {
				Integer fundedAmountInt = Integer.parseInt(fundedAmount);
				fundedAmountInt = fundedAmountInt * 10000;
				fundedAmount = String.valueOf(fundedAmountInt);
			}
		}
//		else {
//			String[] fundedAmounts = fundedAmount.split("\\.");
//			if(fundedAmounts[0].length()>=1 && fundedAmounts[0].length()<3) {
////				BigDecimal b1 = new BigDecimal(Double.parseDouble(fundedAmount));
////				BigDecimal b2 = new BigDecimal(Double.parseDouble("10000"));
////				double fundedAmountDouble = b1.multiply(b2).doubleValue();
////				fundedAmount = String.valueOf(fundedAmountDouble);
//				
//				double fundedAmountDouble = Double.parseDouble(fundedAmount);
//				fundedAmountDouble = fundedAmountDouble * 10000;
//				fundedAmount = String.valueOf(fundedAmountDouble);
//			}
//		}
		return fundedAmount;
	}
	
	/**
	 * 返回响应url内容
	 * @return
	 */
	public static Map<String,Object> getHttpProxyIp(int count){
		String proxyIpUrlApi = "http://api.xdaili.cn/xdaili-api//greatRecharge/getGreatIp?spiderId=ea23eb23e7c844ba9e8667b8ce6d91de&orderno=YZ2018650732aNUVXS&returnType=2&count=1";
//		proxyIpUrlApi = "http://api.xdaili.cn/xdaili-api//privateProxy/getDynamicIP/DD20187221334ubrfyr/c70c52387db611e7bcaf7cd30abda612?returnType=2";
//		proxyIpUrlApi = "http://api.xdaili.cn/xdaili-api//privateProxy/applyStaticProxy?spiderId=dc661dca4a3a406898ee5681b794730c&returnType=2&count=1";
		Map<String,Object> proxyIpMap = new HashMap<String,Object>();
		String result = "";
		try {
			io.github.biezhi.elves.ok.http.Response okHttpResponse = FastHttpClient
						.get()
						.url(proxyIpUrlApi)
						.build()
						.execute();
			result = okHttpResponse.string();
			if(!StringUtils.isNullOrEmpty(result)){
				JSONObject jsonObj = JSON.parseObject(result);
				if("0".equals(jsonObj.getString("ERRORCODE"))) {
					JSONArray jsonArrayResult = JSONArray.parseArray(jsonObj.getString("RESULT"));
					JSONObject jsonResult = JSON.parseObject(jsonArrayResult.getString(0));
					if (jsonResult.containsKey("ip") && jsonResult.containsKey("port")) {
						proxyIpMap.put("proxyHost", jsonResult.getString("ip"));
						proxyIpMap.put("proxyPort", jsonResult.getInteger("port"));
					}
					if (jsonResult.containsKey("wanIp") && jsonResult.containsKey("proxyport")) {
						proxyIpMap.put("proxyHost", jsonResult.getString("wanIp"));
						proxyIpMap.put("proxyPort", jsonResult.getInteger("proxyport"));
					}
				}
			}
		} catch (Exception e) {
			System.out.println("获取代理ip接口返回数据格式错误，异常信息{{}}==>" + "接口返回的结果内容：" + result  + StringUtils.getErrorInfoFromException(e));
			count++;
			if(count<3){
				getHttpProxyIp(count);
			}else{
				System.out.println("调用次数" + count + "，获取代理ip接口返回数据格式一直错误，程序自动停止！！！");
			}
		}
		return proxyIpMap;
	}
	
	/**
	 * 检测程序
	 * @param processName
	 * @return	找到返回true,没找到返回false
	 */
	public static boolean findProcess(String processName){
		BufferedReader br =null;
		try{
			Process proc = Runtime.getRuntime().exec(System.getenv("windir") + "\\system32\\tasklist.exe");
			br = new BufferedReader(new InputStreamReader(proc.getInputStream()));
			String line;
			while((line = br.readLine())!=null){
				if(line.contains(processName)){
					System.out.println("找到" + processName + "程序。。。。。。");
					return true;
				}
			}
			return false;
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}finally {
			if(br!=null){
				try{
					br.close();
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}
	}
	
	/**
	 * 检测并杀掉程序
	 * @param processName
	 * @return	找到返回true,没找到返回false
	 */
	public static boolean findAndKillProcess(String processName){
		BufferedReader br =null;
		try{
			Process proc = Runtime.getRuntime().exec(System.getenv("windir") + "\\system32\\tasklist.exe");
			br = new BufferedReader(new InputStreamReader(proc.getInputStream()));
			String line;
			while((line = br.readLine())!=null){
				if(line.contains(processName)){
					System.out.println("找到" + processName + "程序，先杀掉之前程序。。。。。。");
					WindowsUtils.tryToKillByName(Constants.CHROME_DRIVER_PROCESS_NAME);
					System.out.println("已杀掉此" + processName + "程序。。。。。。");
					return true;
				}
			}
			return false;
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}finally {
			if(br!=null){
				try{
					br.close();
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}
	}
	
	/**
	 * 获取http协议返回的json数据
	 * @param cmsAsynUrl
	 * @param requestEntnameVal
	 * @return
	 */
	public static String getQccGetHttpForJsonData(String cmsAsynUrl,String requestEntnameVal){
		//返回响应url内容
		String jsonStr = HttpUtil.getQccGetHttpReponseBody(cmsAsynUrl);
		if(!StringUtils.isNullOrEmpty(jsonStr)){
			try{
				JSONObject.parseObject(jsonStr);
				return jsonStr;
			}catch(Exception e){
				System.err.println("获取企查查json数据异常，开始重新调用getQccGetHttpForJsonData方法。。。。。。");
				return getQccGetHttpForJsonData(cmsAsynUrl,requestEntnameVal);
			}
		}
		return jsonStr;
	}
	
	/**
	 * 通过http方式，获取html数据
	 * @param requestUrl
	 * @return
	 */
	public static String getHttpForDataContent(String requestUrl) {
		String responseBody = getHttpReponseBody(requestUrl);
		return responseBody;
	}
	
	/**
	 * 返回响应url内容
	 * @return
	 */
	public static String getHttpReponseBody(String requestUrl){
		String jsonStr = "";
		try {
			System.out.println("获取url内容时，先休眠5000毫秒......");
			Thread.sleep(5000);
			System.out.println("已休眠5000毫秒，开始获取url内容===>");
			String qccCookie = QccSelenium.reloadQccCookie(requestUrl);
//			System.out.println(this.getClass() + ".getHttpReponseBody方法，qccCookie{{}}==>" + qccCookie);
			io.github.biezhi.elves.ok.http.Response okHttpResponse;
			if(!Constants.IS_PROXY){
				okHttpResponse = FastHttpClient
						.get()
						.addHeader("cookie", qccCookie)
						.url(requestUrl)
						.build()
						.execute();
			}else{
				Proxy proxy = new Proxy(Proxy.Type.HTTP,new InetSocketAddress(Constants.PROXY_IP, Constants.PROXY_PORT));
				okHttpResponse = FastHttpClient
						.newBuilder()
						.proxy(proxy)
						.build()
						.get().addHeader("cookie", qccCookie)
						.url(requestUrl)
						.build()
						.execute();
			}
			jsonStr = okHttpResponse.string();
			if("[]".equals(jsonStr)){
				jsonStr = "";
			}
			//判断是否为json格式
			boolean isJson = StringUtils.isJsonFormat(jsonStr);
			if(!isJson){
				String scriptRequestUrl = requestUrl.replace("http://www.qichacha.com/", "http://www.qichacha.com/index_verify?type=companysearch&back=/");
				String scriptStr = "<script>window.location.href='" + scriptRequestUrl +"';</script>";
				
				if(scriptStr.equals(jsonStr)){
//					System.out.println("过于频繁调用企查查，超出企查查询次数，暂时休眠，需人工干预，休眠10000毫秒......");
//					Thread.sleep(10000);
					Constants.QCC_PAQU_STATE = "1";
					jsonStr = getHttpReponseBody(scriptRequestUrl);
				}else{
					if(StringUtils.isNullOrEmpty(jsonStr)){
						Constants.QCC_PAQU_STATE = "2";
						jsonStr = getHttpReponseBody(scriptRequestUrl);
					}else{
						Document doc = Jsoup.parse(jsonStr);
						Elements normalLoginElements = doc.select("#normalLoginPanel");
						if((normalLoginElements!=null && normalLoginElements.size()>0)){
							Constants.QCC_PAQU_STATE = "2";
							jsonStr = getHttpReponseBody(requestUrl);
						}
					}
				}
			}
		} catch (SocketTimeoutException e) {
			System.err.println("io.github.biezhi.elves.spider.getHttpReponseBody，SocketTimeoutException，返回响应url内容，链接串为:" + requestUrl + "{{}}==>" + StringUtils.getErrorInfoFromException(e));
			
			if(Constants.IS_PROXY){
				System.out.println("io.github.biezhi.elves.spider.getHttpReponseBody，网络超时，休眠5000毫秒后，重新再调用......");
				try {
					Thread.sleep(5000);
					System.out.println("io.github.biezhi.elves.spider.getHttpReponseBody，已休眠5000毫秒，开始重新再调用getHttpReponseBody方法===>");
					Constants.QCC_PAQU_STATE = "2";
					getHttpReponseBody(requestUrl);
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
			}
		} catch (Exception e) {
			System.err.println("io.github.biezhi.elves.spider.getHttpReponseBody，返回响应url内容，链接串为:" + requestUrl + "{{}}==>" + StringUtils.getErrorInfoFromException(e));
			
			System.out.println("io.github.biezhi.elves.spider.getHttpReponseBody，休眠5000毫秒后，重新再调用......");
			try {
				Thread.sleep(5000);
				System.out.println("io.github.biezhi.elves.spider.getHttpReponseBody，已休眠5000毫秒，开始重新再调用getHttpReponseBody方法===>");
				getHttpReponseBody(requestUrl);
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}
		}
		return jsonStr;
	}
	
	/**
	 * 提取html内容里面的日期数据
	 * @param targetConent
	 * @return
	 */
	public static String regexDateByHtml(String targetConent) {
		String result = "";
		String utilRegex = "\\d{4}年\\d{1,2}月\\d{1,2}日 至 ";
//		utilRegex = "\\d{4}年\\d{2}月\\d{2}日 至 \\d{4}年\\d{2}月\\d{2}日 期间（上午\\d{2}:\\d{2}至\\d{2}:\\d{2},下午\\d{2}:\\d{2}至\\d{2}:\\d{2}";
		Pattern pattern = Pattern.compile(utilRegex);
		Matcher matcher = pattern.matcher(targetConent);
		while (matcher.find()) {
			result = matcher.group().replace("期间（", "");
			result = result.replaceAll("\\s*", "").replace("起至", "").replace("至", "");
		}
		if (isNullOrEmpty(result)) {
			utilRegex = "\\d{4}年\\d{1,2}月\\d{1,2}日起至";
//			utilRegex = "\\d{4}年\\d{1,2}月\\d{1,2}日起至\\d{4}年\\d{1,2}月\\d{1,2}日 期间（";
			pattern = Pattern.compile(utilRegex);
			matcher = pattern.matcher(targetConent);
			while (matcher.find()) {
				result = matcher.group().replace("期间（", "");
				result = result.replaceAll("\\s*", "").replace("起至", "").replace("至", "");
			}
		}
		if (isNullOrEmpty(result)) {
			utilRegex = "\\d{4}年\\d{1,2}月\\d{1,2}日至";
//			utilRegex = "\\d{4}年\\d{1,2}月\\d{1,2}日至\\d{4}年\\d{1,2}月\\d{1,2}日 期间（";
			pattern = Pattern.compile(utilRegex);
			matcher = pattern.matcher(targetConent);
			while (matcher.find()) {
				result = matcher.group().replace("期间（", "");
				result = result.replaceAll("\\s*", "").replace("起至", "").replace("至", "");
			}
		}
		return result;
	}
	
	/**
	 * 匹配项目编号
	 * @param targetConent
	 */
	public static String matchProjectCode(String targetConent) {
		String result = "";
		try {
			String utilRegex = "[a-zA-Z0-9-]{12,20}+";
			Pattern pattern = Pattern.compile(utilRegex);
			Matcher matcher = pattern.matcher(targetConent);
			while (matcher.find()) {
				result = matcher.group();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * 匹配指定目标内容
	 */
	public static String matchTargetContent(String targetConent) {
		String result = "";
		try {
//			targetConent = "广东省政府采购中心  受 韩山师范学院的委托，对 大数据产教融合应用型人才培养建设项目 进行公开招标采购，欢迎符合资格条件的供应商投标。";
//			targetConent = "国义招标股份有限公司   受 中山大学附属肿瘤医院的委托，对 肿瘤影像大数据的移动互联网应用体系建设项目（中山大学附属肿瘤医院采购影像大数据挖掘分析系统） 进行公开招标采购，欢迎符合资格条件的供应商投标。";
//			targetConent = "广东元正招标采购有限公司受广东省农业厅的委托，对广东省网络涉农舆情监测分析大数据平台建设项目进行公开招标采购，欢迎符合资格条件的供应商投标。";
//			System.out.println("原话：" + targetConent);
			String utilRegex = "受 [\\s\\S]+";
			Pattern pattern = Pattern.compile(utilRegex);
			Matcher matcher = pattern.matcher(targetConent);
			while (matcher.find()) {
				result = matcher.group();
				result = result.replace("受 ", "");
				result = result.replace("的委托", "");
			}
			if (StringUtils.isNullOrEmpty(result)) {
				utilRegex = "受[\\s\\S]+";
				pattern = Pattern.compile(utilRegex);
				matcher = pattern.matcher(targetConent);
				while (matcher.find()) {
					result = matcher.group();
					result = result.replace("受", "");
					result = result.replace("的委托", "");
				}
			}
//			System.out.println(result);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return  result;
	}
	
	/**
	 *  匹配中标人名称
	 */
	public static String matchWinBiddingName(String targetConent) {
		try {
			String resultString = "";
			StringBuffer resultBuffer = new StringBuffer();
//			targetConent = "1：中标供应商名称  深圳华数机器人有限公司  法人代表  熊清平  地址  广东省深圳市南山区高新区南区华中科技大学深圳产学研基地大楼A座十一层A1101-A1103    (（包组一）)"
//					+"2：中标供应商名称  巨轮智能装备股份有限公司  法人代表  吴潮忠  地址  广东省揭东经济开发区5号路中段    (（包组二）)";
			//System.out.println("原话：" + targetConent);
			targetConent = targetConent.replaceAll("\\s*", "").replace("&nbsp;", "");
			//System.out.println("去空格："+targetConent);
			String utilRegex = "中标供应商名称<u>[\\u4e00-\\u9fa5]+</u>法人代表";
			Pattern pattern = Pattern.compile(utilRegex);
			Matcher matcher = pattern.matcher(targetConent);
			while (matcher.find()) {
				String result = matcher.group();
				result = result.replace("中标供应商名称<u>", "");
				result = result.replace("</u>法人代表", "");
				resultBuffer.append(result).append(",");
			}
			resultString = resultBuffer.toString();
			if(resultString.lastIndexOf(",") != -1) {
				resultString = resultString.substring(0, resultString.lastIndexOf(","));
			}
			return resultString;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 匹配中标金额
	 * @param args
	 */
	public static List<String> matchWinningBidPrice(String targetConent,int length){
		//标签根据</tr>分隔
		String[] splitTr = targetConent.split("</tr>");
		List<String> trList = new ArrayList<String>();
		for (int i = 1; i < length+1; i++) {
			trList.add(splitTr[i]);
		}
		//根据</td>分隔
		List<String> tdList = new ArrayList<String>();
		for (String tr : trList) {
			String[] splitTd = tr.split("</td>");
			String tdHtml = splitTd[splitTd.length-1];
			String utilRegex = "中标供应商名称<u>[\\u4e00-\\u9fa5]+</u>法人代表";
			Pattern pattern = Pattern.compile(utilRegex);
			Matcher matcher = pattern.matcher(tdHtml);
		}
		
/*		try {
			String resultString = "";
			StringBuffer resultBuffer = new StringBuffer();
			targetConent = targetConent.replaceAll("\\s*", "").replace("&nbsp;", "");
			String utilRegex = "中标供应商名称<u>[\\u4e00-\\u9fa5]+</u>法人代表";
			Pattern pattern = Pattern.compile(utilRegex);
			Matcher matcher = pattern.matcher(targetConent);
			while (matcher.find()) {
				String result = matcher.group();
				result = result.replace("中标供应商名称<u>", "");
				result = result.replace("</u>法人代表", "");
				resultBuffer.append(result).append(",");
			}
			resultString = resultBuffer.toString();
			if(resultString.lastIndexOf(",") != -1) {
				resultString = resultString.substring(0, resultString.lastIndexOf(","));
			}
			return resultString;
		
		} catch (Exception e) {
			e.printStackTrace();
		}*/
		return null;
	}
	
	/**
	 * 匹配项目预算
	 * @param targetConent
	 */
	public static String matchProjectPrice(String targetConent) {
		String result = "";
		try {
			targetConent = "三、采购预算：40万元"
				+"四、项目内容及需求：a(采购项目技术要求)"
				+"大数据工程设计,详见用户需求书。"
				+"供应商网上报名须知：供应商可登陆www.gpcgd.com广东省政府采购中心网站，点击网站右下方";
			System.out.println("原话：" + result);
			String utilRegex = "采购预算：[0-9]+万元";
			Pattern pattern = Pattern.compile(utilRegex);
			Matcher matcher = pattern.matcher(targetConent);
			while (matcher.find()) {
				result = matcher.group();
				result = result.replace("采购预算：", "");
			}
//			System.out.println(result);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * 匹配更正公告
	 * @param str
	 * @param start
	 * @param endwith
	 * @return
	 */
	public static String matchChangeNoticeContent(String str, String start, String endwith){
	    if (TextUtils.isEmpty(str)) {
	        return "";
	    }
	    String result = "";
	    if (str.contains(start)) {
	        String s1 = str.split(start)[1];
	        if (endwith == null || "".equals(endwith)) {
	            result = s1;
	        } else {
	            String s2[] = s1.split(endwith);
	            if (s2 != null) {
	                result = s2[0];
	            }
	        }
	    }
	    return result;
	}
	
	/**
	 * 匹配指定数据
	 * @param targetConent
	 * @param regex
	 * @return
	 */
	public static String regexData(String targetContent, String regex) {
		try {
			String resultString = "";
			StringBuffer resultBuffer = new StringBuffer();
//			targetConent = "1：中标供应商名称  深圳华数机器人有限公司  法人代表  熊清平  地址  广东省深圳市南山区高新区南区华中科技大学深圳产学研基地大楼A座十一层A1101-A1103    (（包组一）)"
//					+"2：中标供应商名称  巨轮智能装备股份有限公司  法人代表  吴潮忠  地址  广东省揭东经济开发区5号路中段    (（包组二）)";
			//System.out.println("原话：" + targetConent);
//			targetContent = targetContent.replaceAll("\\s*", "").replace("&nbsp;", "");
			//System.out.println("去空格："+targetConent);
			Pattern pattern = Pattern.compile(regex);
			Matcher matcher = pattern.matcher(targetContent);
			while (matcher.find()) {
				String result = matcher.group();
				resultBuffer.append(result).append(",");
			}
			resultString = resultBuffer.toString();
			if(resultString.lastIndexOf(",") != -1) {
				resultString = resultString.substring(0, resultString.lastIndexOf(","));
			}
			return resultString;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static String matchWinBidTime(String targetContent) {
		String result="";
		String utilRegex = "评审日期：([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8])))";
		Pattern pattern = Pattern.compile(utilRegex);
		Matcher matcher = pattern.matcher(targetContent);
		while (matcher.find()) {
			result = matcher.group();
			result = result.replace("评审日期：", "");
		}
		return result;
	}
	
	public static void main(String[] args) {
		getHttpProxyIp(1);
	}


}